<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="policyTitle">
        <el-input
          v-model="queryParams.policyTitle"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="policyType">
        <el-select v-model="queryParams.policyType" placeholder="请选择类型" clearable size="small">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <!--<el-form-item label="内容" prop="policyContent">
        <el-input
          v-model="queryParams.policyContent"
          placeholder="请输入内容"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布部门ID" prop="issueDepartmentId">
        <el-input
          v-model="queryParams.issueDepartmentId"
          placeholder="请输入发布部门ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布人ID" prop="issueUserId">
        <el-input
          v-model="queryParams.issueUserId"
          placeholder="请输入发布人ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布时间" prop="issueTime">
        <el-date-picker clearable size="small" style="width: 200px"
                        v-model="queryParams.issueTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择发布时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="接收人ID" prop="receiveUserId">
        <el-input
          v-model="queryParams.receiveUserId"
          placeholder="请输入接收人ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="接收部门ID" prop="receiveDepartmentId">
        <el-input
          v-model="queryParams.receiveDepartmentId"
          placeholder="请输入接收部门ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <!--<el-form-item label="置顶" prop="istop">
        <el-input
          v-model="queryParams.istop"
          placeholder="请输入置顶"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建人" prop="createName">
        <el-input
          v-model="queryParams.createName"
          placeholder="请输入创建人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="更新人" prop="updateName">
        <el-input
          v-model="queryParams.updateName"
          placeholder="请输入更新人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remake">
        <el-input
          v-model="queryParams.remake"
          placeholder="请输入备注"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:statute:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:statute:edit']"
        >修改</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:statute:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:statute:export']"
        >导出</el-button>
      </el-col>
      <div class="top-right-btn">
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="handleQuery" />
        </el-tooltip>
        <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
          <el-button size="mini" circle icon="el-icon-search" @click="showSearch=!showSearch" />
        </el-tooltip>
      </div>
    </el-row>

    <el-table @row-dblclick="rowDetails" v-loading="loading" :data="statuteList" @selection-change="handleSelectionChange" :max-height="height">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" width="70" align="center" fixed="left">
        <template scope="scope"> <span>{{scope.$index + (queryParams.pageNum - 1) * queryParams.pageSize + 1}} </span> </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="policyTitle" :show-overflow-tooltip="true" min-width="200" />
      <el-table-column label="类型" align="center" prop="policyType" :formatter="typeFormat" />
<!--      <el-table-column label="内容" align="center" prop="policyContent" :formatter="contentFormat" :show-overflow-tooltip="true" />-->
      <el-table-column label="发布部门" align="center" prop="issueDepartmentName" :show-overflow-tooltip="true" />
      <el-table-column label="发布人" align="center" prop="issueUserName" :show-overflow-tooltip="true" />
      <el-table-column label="发布时间" align="center" prop="issueTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.issueTime }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="接收人" align="center" prop="receiveUserName" :show-overflow-tooltip="true" :formatter="receiveUserFormat" />-->
<!--      <el-table-column label="接收部门" align="center" prop="receiveDepartmentName" :show-overflow-tooltip="true" :formatter="receiveDepartmentFormat" />-->
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="置顶" align="center" prop="istop" >
        <template slot-scope="scope">
          <!--<el-switch
            v-model="scope.row.istop"
            active-value="1"
            inactive-value="0"
            @change="handleTopChange(scope.row)"
          ></el-switch>-->
          <a class='el-icon-upload2' :style="{color:(scope.row.istop==0?'#959595':'#0098ff')}" style="font-size: 25px" @click="handleTopChange(scope.row)"></a>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="downloadAttachment(scope.row)"
          >下载</el-button>
          <router-link :to="'/statute/type/data/' + scope.row.policyId" style="margin: 0 10px 0 10px">
<!--          <router-link :to="{name:'noticeData',params:{row:scope.row}}">-->
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
            >查看</el-button>
          </router-link>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:statute:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:statute:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改政策法规对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="policyTitle">
          <el-input v-model="form.policyTitle" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="类型" prop="policyType">
          <el-select v-model="form.policyType" placeholder="请选择类型">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="policyContent">
          <Editor v-model="form.policyContent" />
        </el-form-item>
        <div style="padding-top:50px">
          <el-form-item label="视频地址">
            <el-upload
              ref="upload"
              :action="upload.url"
              :headers="upload.headers"
              :show-file-list="false"
              :on-success="handleFileSuccess">
              <el-button slot="trigger" size="small" type="primary">上传视频文件</el-button>
              <div slot="tip" class="el-upload__tip">如果内容总需要添加视频，请先通过上传视频获取视频地址，复制后通过文本编辑器插入即可！</div>
            </el-upload>
          </el-form-item>
        </div>
        <el-form-item label="上传附件">
          <el-upload
            ref="upload"
            :action="upload.url"
            :headers="upload.headers"
            multiple
            :file-list="upload.fileList"
            :on-success="annexSuccess"
            :on-remove="annexRemove">
            <el-button slot="trigger" size="small" type="primary">上传附件</el-button>
          </el-upload>
        </el-form-item>
        <!--<el-form-item label="发布部门ID" prop="issueDepartmentId">
          <el-input v-model="form.issueDepartmentId" placeholder="请输入发布部门ID" />
        </el-form-item>
        <el-form-item label="发布人ID" prop="issueUserId">
          <el-input v-model="form.issueUserId" placeholder="请输入发布人ID" />
        </el-form-item>
        <el-form-item label="发布时间" prop="issueTime">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.issueTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择发布时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="接收人ID" prop="receiveUserId">
          <el-input v-model="form.receiveUserId" placeholder="请输入接收人ID" />
        </el-form-item>
        <el-form-item label="接收部门ID" prop="receiveDepartmentId">
          <el-input v-model="form.receiveDepartmentId" placeholder="请输入接收部门ID" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="置顶" prop="istop">
          <el-input v-model="form.istop" placeholder="请输入置顶" />
        </el-form-item>
        <el-form-item label="创建人" prop="createName">
          <el-input v-model="form.createName" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="更新人" prop="updateName">
          <el-input v-model="form.updateName" placeholder="请输入更新人" />
        </el-form-item>
        <el-form-item label="备注" prop="remake">
          <el-input v-model="form.remake" placeholder="请输入备注" />
        </el-form-item>-->
        <el-form-item label="接收人">
          <el-tree
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            empty-text="加载中，请稍后"
            :props="defaultProps"
          ></el-tree>
          <div slot="tip" class="el-upload__tip">可多选，未指定为对所有人公开</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('0')">发 布</el-button>
        <el-button type="primary" @click="submitForm('3')">提 交</el-button>
        <el-button type="primary" @click="submitForm('1')">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listStatute, getStatute, delStatute, addStatute, updateStatute, exportStatute, changeTop, treeselect, getFile } from "@/api/system/statute";
  import Editor from '@/components/Editor';
  import { getToken } from "@/utils/auth";
  import JSZip from 'jszip'
  import FileSaver from 'file-saver'

  export default {
    name: "Statute",
    components: {
      Editor
    },
    data() {
      return {
        height: (document.documentElement.clientHeight || document.body.clientHeight)-260,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        names: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 政策法规表格数据
        statuteList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 状态数据字典
        statusOptions: [],
        // 类型数据字典
        typeOptions: [],
        // 接受人员部门列表
        menuOptions: [],

        defaultProps: {
          children: "children",
          label: "label"
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          policyTitle: null,
          policyType: null,
          policyContent: null,
          issueDepartmentId: null,
          issueUserId: null,
          issueTime: null,
          receiveUserId: null,
          receiveDepartmentId: null,
          status: null,
          istop: null,
          createName: null,
          updateName: null,
          remake: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          policyTitle: [
            { required: true, message: "标题不能为空", trigger: "blur" }
          ],
          policyType: [
            { required: true, message: "请选择类型", trigger: "blur" }
          ],
          policyContent: [
            { required: true, message: "内容不能为空", trigger: "blur" }
          ],
          /*issueDepartmentId: [
            { required: true, message: "发布部门ID不能为空", trigger: "blur" }
          ],
          issueUserId: [
            { required: true, message: "发布人ID不能为空", trigger: "blur" }
          ],
          receiveUserId: [
            { required: true, message: "接收人ID不能为空", trigger: "blur" }
          ],
          receiveDepartmentId: [
            { required: true, message: "接收部门ID不能为空", trigger: "blur" }
          ],*/
        },
        upload: {
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/common/upload",
          // 上传的文件列表
          fileList: []
        },
      };
    },
    created() {
      this.getList();
      this.getDicts("t_policy_statute_status").then(response => {
        this.statusOptions = response.data;
      });
      this.getDicts("t_policy_statute_type").then(response => {
        this.typeOptions = response.data;
      });
    },
    methods: {
      /** 查询政策法规列表 */
      getList() {
        this.loading = true;
        listStatute(this.queryParams).then(response => {
          this.statuteList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        if (this.$refs.menu != undefined) {
          this.$refs.menu.setCheckedKeys([]);
        }
        this.form = {
          policyId: null,
          policyTitle: null,
          policyType: null,
          policyContent: null,
          issueDepartmentId: null,
          issueUserId: null,
          issueTime: null,
          receiveUserId: null,
          receiveDepartmentId: null,
          status: "0",
          istop: null,
          createName: null,
          updateName: null,
          updateTime: null,
          remake: null,
          fileList: [],
          menuIds: [],
        };
        this.upload.fileList = [];
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.policyId)
        this.names = selection.map(item => item.policyTitle)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.$router.push({name:'statuteAdd', params:{ row: '' }});
/*        this.reset();
        this.getMenuTreeselect();
        this.open = true;
        this.title = "添加政策法规";*/
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        if (row.status == 0){
          this.msgSuccess("已发布的文章不能再进行编辑！");
          return;
        }
        this.$router.push({name:'statuteEdit', params:{ row: row  }});
        /*this.reset();
        this.getMenuTreeselect();
        const policyId = row.policyId || this.ids
        getStatute(policyId).then(response => {
          this.form = response.data;
          this.form.policyType = ''+this.form.policyType+'';
          this.open = true;
          this.$nextTick(() => {
            const arr = [];
            if (this.form.receiveUserId != null){
              var userids = this.form.receiveUserId.split(",");
              for (var k=0;k<userids.length;k++){
                arr.push(parseInt(userids[k]));
              }
            }
            this.$refs.menu.setCheckedKeys(userids);//获取已经设置的资源后渲染
          });
          this.$nextTick(() => {
            const arr = [];
            if (row.attachmentName != null){
              var attachmentName = row.attachmentName.split(",");
              var attachmentUrl = row.attachmentUrl.split(",");
              var attachmentPath = row.attachmentPath.split(",");
              for (var k=0;k<attachmentName.length;k++){
                arr.push({
                  name:attachmentName[k],
                  response:{
                    fileName:attachmentPath[k],
                    url:attachmentUrl[k],
                  }
                });
              }
            }
            this.upload.fileList=arr;
            this.form.fileList=arr;
          });
          this.title = "修改政策法规";
        });*/
      },
      /** 提交按钮 */
      submitForm:function(statu) {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.policyId != null) {
              this.form.status = statu;
              this.form.menuIds = this.getMenuAllCheckedKeys();
              updateStatute(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }
              });
            } else {
              this.form.status = statu;
              this.form.menuIds = this.getMenuAllCheckedKeys();
              addStatute(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const policyIds = row.policyId || this.ids;
        const policyTitles = row.policyTitle || this.names;
        this.$confirm('是否确认删除政策法规标题为"' + policyTitles + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delStatute(policyIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有政策法规数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportStatute(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.msgSuccess(response.msg);
        this.$alert(response.url, '视频地址', {
          dangerouslyUseHTMLString: true
        });
      },
      // 附件上传成功处理
      annexSuccess(response, file, fileList) {
        this.form.fileList=fileList
      },
      // 附件上传失败处理
      annexRemove(file, fileList) {
        this.form.fileList=fileList
      },
      /** 查询菜单树结构 */
      getMenuTreeselect() {
        treeselect().then(response => {
          this.menuOptions = response.data;
        });
      },
      // 所有人员节点数据
      getMenuAllCheckedKeys() {
        // 目前被选中的菜单节点
        let checkedKeys = this.$refs.menu.getHalfCheckedKeys();
        // 半选中的菜单节点
        let halfCheckedKeys = this.$refs.menu.getCheckedKeys();
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
        return checkedKeys;
      },
      // 状态字典翻译
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status);
      },
      // 类型字典翻译
      typeFormat(row, column) {
        return this.selectDictLabel(this.typeOptions, row.policyType);
      },
      contentFormat(row){
        return row.policyContent.replace(/<[^>]+>/g, '');
      },
      // 接收人为空判断
      receiveUserFormat(row,colum){
        return row.receiveUserName == null?"所有人":row.receiveUserName;
      },
      // 接收部门为空判断
      receiveDepartmentFormat(row,colum){
        return row.receiveDepartmentName == null?"所有部门":row.receiveDepartmentName;
      },
      // 置顶修改
      /*handleTopChange(row) {
        changeTop(row.policyId,row.istop);
        return this.handleQuery();
      },*/
      handleTopChange(row) {
        var num = 0;
        row.istop==1?num=0:num=1;
        changeTop(row.policyId,num);
        row.istop=num;
        return this.handleQuery();
      },
      //下载
      downloadAttachment(row) {
        if (row.attachmentName != null){
          var attachmentName = row.attachmentName.split(",");
          var attachmentUrl = row.attachmentUrl.split(",");
          const zip = new JSZip();
          const cache = {};
          const promises = [];
          for (var i=0;i<attachmentUrl.length;i++){
            setTimeout((function time(i){
              const promise = getFile(attachmentUrl[i]).then(data => { // 下载文件, 并存成ArrayBuffer对象
                const file_name = attachmentName[i]; // 获取文件名
                zip.file(file_name, data, { binary: true }); // 逐个添加文件
                cache[file_name] = data
              })
              promises.push(promise)
            })(i), 0);
          }
          Promise.all(promises).then(() => {
            zip.generateAsync({type:"blob"}).then(content => { // 生成二进制流
              FileSaver.saveAs(content, "附件.zip") // 利用file-saver保存文件
            })
          })
        }else {
          this.msgSuccess("无附件可下载！")
        }
      },
      //双击查看
      rowDetails(row, column, event){
        this.$router.push({name:'StatuteDetails', params:{ policyId: row.policyId  }});
      },
    }
  };
</script>
